package sample.ui

import android.app.Dialog
import android.content.ClipboardManager
import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import com.netease.core.R
import kotlinx.coroutines.script.tes.setOnClickCallback
import kotlinx.coroutines.script.tes.toast

class SetupCKV2Dialog private constructor(context: Context, theme: Int) : Dialog(context, theme) {
    interface OnCDKeyInputListener {
        fun onInput(value: String)
    }

    class Builder(private val context: Context) {
        private val canCancel = true
        var callback: OnCDKeyInputListener? = null

        fun setCallback(listener: OnCDKeyInputListener): Builder {
            callback = listener
            return this
        }

        fun create(): SetupCKV2Dialog {
            val dialog = SetupCKV2Dialog(context, R.style.Theme_Light_NoTitle_Dialog)
            val window = dialog.window
            if (window != null) {
                window.setWindowAnimations(R.style.Animation_Bottom_Rising)
                window.decorView.setPadding(0, 0, 0, 0)
                val lp = window.attributes
                lp.width = WindowManager.LayoutParams.MATCH_PARENT
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT
                window.attributes = lp
                window.setGravity(Gravity.BOTTOM)
            }
            val view = LayoutInflater.from(context).inflate(R.layout.cv2ad, null)
            val viewCdkValue = view.findViewById<TextView>(R.id.cdkValue)
            view.findViewById<View>(R.id.submit).setOnClickCallback {
                dialog.dismiss()
                val value = viewCdkValue.text.trim().toString()
                if (value.length == 36) {
                    callback?.onInput(value)
                } else if (value.isNotEmpty()) {
                    toast("卡密不存在")
                }
            }
            val clipboard =
                context.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            val clipSize = clipboard.primaryClip?.itemCount ?: 0
            if (clipSize > 0) {
                val clipData = clipboard.primaryClip?.getItemAt(0)
                val clipStr = clipData?.text.toString()
                // 279349db-3053-4ad3-8fa6-8208c607e42b
                if (clipStr.length == 36) viewCdkValue.text = clipStr
            }
            dialog.setContentView(view)
            dialog.setCanceledOnTouchOutside(canCancel)
            dialog.setCancelable(canCancel)
            return dialog
        }
    }
}